<template>
  <!-- 用户管理 -- 机构管理 -- 添加用户/编辑用户-->
  <div class="page-operate">
    <!-- 位置模块 -->
    <HeadTop></HeadTop>
    <div class="page-head">
      <span class="operate-text">编辑用户</span>
      <div class="operate-box">
        <button class="submit" @click="submitUserMsg">提交</button>
        <button @click="back()">关闭</button>
      </div>
    </div>
    <div class="content-area">
      <div class="form-detail add-user" style="padding-top: 60px;">
        <div class="page-form">
          <el-form :inline="true" status-icon class="my-form my-form-600" ref="myForm" :model="myForm"
                   label-width="120px" size="medium">
            <el-form-item label="用户名:" required>
              <el-input v-model="myForm.username"></el-input>
              <p class="password-warning" v-show="uid !== '0'">如果不需要修改密码,请不要填写密码与确定密码</p>
            </el-form-item>

            <el-form-item label="密码:" required>
              <el-input v-model="myForm.pass" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码:" required>
              <el-input v-model="myForm.checkPass" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="选择用户角色:" required>
              <el-select v-model="myForm.role" placeholder="--请选择用户组--">
                <el-option v-for="item in roleArr" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="员工姓名:" required>
              <el-input v-model="myForm.realName "></el-input>
            </el-form-item>
            <el-form-item label="员工手机号码:" required>
              <el-input v-model="myForm.userPhone"></el-input>
            </el-form-item>

            <el-form-item label="权限选择:" required>
              <el-input placeholder="请选择权限" v-model="checkPower" readonly
                        @focus="showAuthorityManage"></el-input>
            </el-form-item>
            <el-form-item label="邮箱:">
              <el-input v-model="myForm.email"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <dialogPowerSet ref="dialogPower" v-on:backstageNeedPower="setPower"></dialogPowerSet>
  </div>
</template>
<style lang="scss" type="text/scss">
  @import '../../../../../style/entry/components/pageChildCommon';

  .select-authority-tree {
    width: 100%;
    height: 300px;
    overflow: auto;
  }

  .add-user form {
    display: flex;
    flex-direction: column;
  }
</style>
<script>
  import com from '../../../../../js/common'
  import md5 from 'js-md5'
  import HeadTop from "../../../../../components/head-top/head-top"

  import {getUserDetail, getUserRbac, updateUserRbac} from '@/api/getData'

  import dialogPowerSet from "../../../../../components/dialogPowerSet/dialogPowerSet"

  import {RoleArr} from '@/js/constant'

  export default {
    components: {
      HeadTop,
      dialogPowerSet
    },
    data() {
      return {
        organId: this.$route.query.organId ? this.$route.query.organId : 0,
        myForm: {
          pass: '',
          checkPass: '',
          username: '',
          realName: '',
          userPhone: '',
          user: '',
          role: '',
          email: '',
          companyName: '',
          regTime: '',
          departmentId: '',
          // 用户权限列表
          auths: [],
          // 是否选择用户角色等级是否大于平台管理员
          isSuper: true,
        },
        // 存储用户信息
        userMsg: {},
        title: '添加用户',
        uid: '0',
        roleArr: [],
        showDialogAuthorityTree: false,
        // 用户所能操作的权限
        userAuthorityTreeData: [],
        // 权限树名称
        defaultProps: {
          children: 'list',
          label: 'name'
        },
        // 用户已有权限
        userHasAuthority: [],
        // 权限code对应权限
        treeObj: {},
        checkPower: '',
        role: Number(com.getStore('role')),
      };
    },
    // 页面装载中
    created() {
      this.getUserMsg()
      this.checkUserRole()
    },
    methods: {
      // 根据登录用户 角色分配
      checkUserRole() {
        const arr = RoleArr
        const role = this.role
        this.roleArr = arr.filter((val) => {
          return val.value < role
        })
      },
      // 获取用户信息
      getUserMsg() {
        const uid = this.$route.query.id
        const userId = this.$route.query.userId

        this.uid = uid
        this.userId = userId
        if (userId !== '0') {
          this.checkPower = '已选择用户权限,点击修改'
          getUserDetail({
            userId: userId,
          }).then((res) => {
            // 存储用户信息
            this.userMsg = res.data.data
            // 存储用户展示信息
            this.myForm = res.data.data
            this.myForm.pass = ''
            this.myForm.checkPass = ''
          }).catch(err => this.$message.error(err.data.message))
        }
      },

      // 显示权限树判断
      showAuthorityManage(val) {
        // 此时获取用户权限
        let param = {}
        param.userId = this.userMsg.userId
        getUserRbac(param).then((res) => {
          const authorityArr = res.data.data
          this.$refs.dialogPower.getEleNeedPower(authorityArr)
        }).catch(err => this.$message.error(err.data.message))
      },
      // 最后设置权限
      setPower(backNeedPower) {
        // 修改用户权限
        let params = {}
        params.auths = backNeedPower
        params.user = {}
        params.user.userId = this.userMsg.userId
        updateUserRbac(params).then((res) => {
          com.mask()
          this.$message.success({
            message: '修改成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$refs.dialogPower.hideDialog()
            }
          })
        }).catch(err => {
          this.$message.error(err.data.message)
          this.$refs.dialogPower.hideDialog()
        })
      },
      // 1.点击提交时
      submitUserMsg() {
        if (!this.checkInput()) {
          return
        }
        if (this.uid !== '0') {
          // 编辑用户
          this.updateUser()
        }
      },
      // 2.校验必备字段输入
      checkInput() {
        // 用户名
        if (this.myForm.username === '') {
          this.$message.warning('请输入用户名')
          return false
        }
        // 密码
        if (this.myForm.pass !== this.myForm.checkPass) {
          this.$message.warning('请保持两次密码一致');
          return false
        }
        // 选择角色
        if (this.myForm.role === '') {
          this.$message.warning('请选择用户角色')
          return false
        }
        // 员工姓名
        if (this.myForm.realName === '') {
          this.$message.warning('请输入员工姓名')
          return false
        }
        // 手机号码
        if (!com.checkMobile(this.myForm.userPhone)) {
          this.$message.warning('请输入正确格式手机号')
          return false
        }

        return true
      },
      // 3.2更新用户信息
      updateUser() {
        const url = `${com.basePath}/usercenter-web/user/update`
        let param = {}
        param = this.myForm
        delete param.auths
        if (this.myForm.pass === '') {
        } else {
          if (this.myForm.pass !== this.myForm.checkPass) {
            this.$message.warning('密码应与确定密码相同')
          } else {
            param.password = md5(this.myForm.pass)
          }
        }
        com.axio.post(url, param).then((res) => {
          com.mask()
          this.$message.success({
            message: '修改成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$router.push(`/manage/systemMgr/organMgr/lookOrganUser?organId=${this.organId}`)
            }
          })
        }).catch((err) => {
          this.$message.error(err.data.message)
        })
      },
      // 返回上一级
      back() {
        this.$router.go(-1)
      },
    }
  }
</script>
